package com.yyaccp.appinfo.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yyaccp.appinfo.domain.BackendUser;
import com.yyaccp.appinfo.domain.DevUser;
import com.yyaccp.appinfo.utils.AjaxResult;
import com.yyaccp.appinfo.utils.Constants;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

public class AppInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        BackendUser backendUser = (BackendUser)session.getAttribute(Constants.USER_SESSION);
        DevUser devUser = (DevUser)session.getAttribute(Constants.DEV_USER_SESSION);
        if(devUser != null){
            return true;
        }else if(backendUser != null){
            return true;
        }else{
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String json = JSONObject.toJSONString(AjaxResult.error("请先登录"));
            out.print(json);
            out.flush();;
            return false;
        }
    }

    /* @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        BackendUser backendUser = (BackendUser)session.getAttribute(Constants.USER_SESSION);
        DevUser devUser = (DevUser)session.getAttribute(Constants.DEV_USER_SESSION);
        if(devUser != null){
            return true;
        }else if(backendUser != null){
            return true;
        }else{
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String json = JSONObject.toJSONString(AjaxResult.error("请先登录"));
            out.print(json);
            out.flush();;
            return false;
        }
    }*/

    /*public boolean preHandle(HttpServletRequest request, HttpServletResponse response,HttpSession session,Object handler) throws Exception{
        BackendUser backendUser = (BackendUser)session.getAttribute(Constants.USER_SESSION);
        DevUser devUser = (DevUser)session.getAttribute(Constants.DEV_USER_SESSION);
        if(devUser != null){
            return true;
        }else if(backendUser != null){
            return true;
        }else{
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String json = JSONObject.toJSONString(AjaxResult.error("请先登录"));
            out.print(json);
            out.flush();;
            return false;
        }
    }*/
}
